package com.bbs.toutiao.controller.admin;


import cn.hutool.core.lang.Assert;
import com.bbs.toutiao.aspect.SysLog;
import com.bbs.toutiao.utils.Jwt;
import com.bbs.toutiao.utils.Result;
import com.bbs.toutiao.vo.user.RegisterVo;
import com.bbs.toutiao.entity.MailEntity;
import com.bbs.toutiao.entity.UserEntity;
import com.bbs.toutiao.utils.MailUtil;
import com.bbs.toutiao.utils.MsgCodeUtil;
import com.bbs.toutiao.exception.BaseException;
import com.bbs.toutiao.exception.ExceptionEnum;
import com.bbs.toutiao.vo.user.LoginRequestVo;
import com.bbs.toutiao.service.admin.impl.UserServiceImpl;
import com.bbs.toutiao.vo.user.LoginResponseVo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Objects;


/**
 * 描述: 用户登录、注册、获取验证码
 * 作者： zhangBin
 * 时间： 2023/9/5 20:16
 * 版本： 1.0
 */

@Slf4j
@RestController
@RequestMapping("/api")
public class AdminUserController {

    @Resource
    private UserServiceImpl userService;
    @Resource
    private MailUtil mailUtil;
    @Resource
    private TemplateEngine templateEngine;


    /**
     * 用户登录
     * 指定查询用户
     **/
    @PostMapping("/loginUser")
    public Result login(@RequestBody LoginRequestVo loginVo) {
        if (Objects.equals(loginVo.getEmail(), "") || Objects.equals(loginVo.getPassword(), "")) {
            throw new BaseException(ExceptionEnum.NOT_NULL);
        }
        UserEntity userEntity = userService.login(loginVo);
        String token = Jwt.getToken(userEntity);
        LoginResponseVo loginResponseVo = new LoginResponseVo();
        loginResponseVo.setUsrId(userEntity.getId());
        loginResponseVo.setToken(token);
        loginResponseVo.setEmail(userEntity.getUserEmail());
        return Result.success("登陆成功", loginResponseVo);
    }


    /**
     * 生成验证码
     * @param responseVo 响应的注册vo
     * @return {@link Result}
     * 作者: zhang
     * Date: 2023/9/17 21:32
     */

    @SysLog("发送邮箱验证码")
    @PostMapping(value = "/email")
    public Result email(@RequestBody RegisterVo responseVo) {
        //生成验证码
        try {
            //断言注册信息不为空
            Assert.notNull(responseVo.getEmail());
            String captcha = MsgCodeUtil.getCode(responseVo.getEmail());
            //注意：Context 类是在包下的。
            Context context = new Context();
            //html中填充动态属性值
            context.setVariable("project", "码农用户");
            context.setVariable("numbers", captcha);
            //注意：process第一个参数名称要和templates下的模板名称一致。要不然会报错
            //org.thymeleaf.exceptions.TemplateInputException: Error resolving template [email]
            String emailContent = templateEngine.process("email", context);

            MailEntity mailEntity = new MailEntity();
            mailEntity.setRecipient(responseVo.getEmail());//接收者
            mailEntity.setSubject("邮箱验证信息");//标题
            //内容主体
            mailEntity.setContent(emailContent);
            mailUtil.sendSimpleMail(mailEntity);
            log.info("验证码已发送至账号：{},验证码为：{}",responseVo.getEmail(),captcha);
            return Result.success("验证码已经发送，注意查收",captcha);
        } catch (IllegalArgumentException e) {
            return Result.error(404, "消息为空");
        }
    }

    /**
     * 用户注册
     *
     * @param registerVo
     * @return 成功，失败
     */
    @PostMapping("/register")
    public Result register(@RequestBody RegisterVo registerVo) {
        try {
            Assert.notBlank(registerVo.getEmail());
            Assert.notBlank(registerVo.getUserName());
            Assert.notBlank(registerVo.getPassword());
            Assert.notBlank(registerVo.getCaptcha());
        } catch (IllegalArgumentException e) {
            throw new BaseException(ExceptionEnum.NOT_NULL);
        }
        MsgCodeUtil.startCleanerCache();//开启定时清理
        log.error("===" + registerVo.getEmail());
        if (!MsgCodeUtil.booleanCode(registerVo.getEmail(), registerVo.getCaptcha())) {
            return Result.error(401, "验证码过期");
        }
        if (userService.registerUser(registerVo)) {
            return Result.success("注册成功");
        }
        return Result.error(401, "注册失败");
    }

}
